package com.wck.car.car;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wck.car.car.service.AppCarTypeService;
import com.wck.car.model.AppCarType;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import javax.annotation.Resource;
import java.util.List;

@Component
public class CarTypePipeline implements Pipeline {

    @Resource
    private AppCarTypeService carTypeService;

    @Override
    public void process(ResultItems resultItems, Task task) {
        String str = resultItems.get("repo");
        String seriesId =  resultItems.get("seriesId");

        JSONArray json = JSON.parseArray(str);
        List<CarResult> list = JSONArray.parseArray(str, CarResult.class);

       if (list != null && list.size() > 0) {
           list.forEach(bean ->{
               if ("在售车型".equals(bean.getName())) {
                   bean.getList().forEach(carType -> {
                       carType.setSeriesId(Integer.parseInt(seriesId));
                       carType.setType(0);
                       if (carTypeService.count(new LambdaQueryWrapper<AppCarType>().eq(AppCarType::getTypeId, carType.getId())) < 1) {
                          AppCarType appCarType = new AppCarType();
                           BeanUtils.copyProperties(carType, appCarType);
                           appCarType.setTypeId(carType.getId());
                           carTypeService.save(appCarType);

                       }
                   });
               } else if ("停售车型".equals(bean.getName())) {
                   bean.getList().forEach(carType -> {
                       carType.setSeriesId(Integer.parseInt(seriesId));
                       carType.setType(1);
                       if (carTypeService.count(new LambdaQueryWrapper<AppCarType>().eq(AppCarType::getTypeId, carType.getId()))  < 1) {
                           AppCarType appCarType = new AppCarType();
                           BeanUtils.copyProperties(carType, appCarType);
                           appCarType.setTypeId(carType.getId());
                           carTypeService.save(appCarType);
                       }
                   });
               }
           });
       }
    }


    public static void main(String[] args) {
        String str = "https://www.autohome.com.cn/ashx/index/GetHomeFindCar.ashx?type=2&format=json&v=1";
        System.out.println(str.substring(str.indexOf("seriesid=")+9,str.indexOf("&format")));
    }

}
